package com.app.community.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.app.community.dto.PersonDTO;
import com.app.community.mapper.PersonMapper;
import com.app.community.model.entity.AliyunClient;
import com.app.community.model.entity.Question;
import com.app.community.model.entity.User;
import com.app.community.util.AliyunOSSUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Date 2020/10/28 22:31
 **/
@Slf4j
@Service
public class PersonService {
    @Autowired
    PersonMapper personMapper;

    // 上传工具
    AliyunOSSUtils ossUtils = new AliyunOSSUtils();
    // 获取阿里云账户
    AliyunClient ossClient = new AliyunClient();

    public PersonDTO selectQuestionAndUser(String userId){
        List<Question> questionList = personMapper.selectQuestion(userId);
        User user = personMapper.selectPerson(userId);
        PersonDTO personDTO = new PersonDTO();
        personDTO.setUser(user);
        personDTO.setQuestionList(questionList);
        return personDTO;
    }

    /**
     * 删除问题，同时删除阿里云中存储的图片
     */
    public void deleteQuestionAndComment(Long questionId,String userId){
        // 删除问题的同时删除阿里云的存储
        // 创建OSSClient实例。
        OSS oss = new OSSClientBuilder().build(ossClient.getEndpoint(), ossClient.getAccessKeyId(), ossClient.getAccessKeySecret());

        // key等同于ObjectName，表示删除OSS文件时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg。
        ObjectListing objectListing = oss.listObjects("hgshequ-bucket", "question/"+questionId);

        // 列举需要删除的文件列表
        List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
        List<String> keys = new ArrayList<>();
        for (OSSObjectSummary s : sums) {
            keys.add(s.getKey());
        }
        // 对keys进行非空判断
        if (keys.isEmpty()){
            log.info("问题号为："+questionId + "的问题没有在阿里云进行图片存储需要删除");
        }else{

            DeleteObjectsResult deleteObjectsResult = oss.deleteObjects(new DeleteObjectsRequest("hgshequ-bucket").withKeys(keys));
            //        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
            // 删除结果(删除了哪些元素)
//        System.out.println(deletedObjects);

        }

        // 该delete方法可以非空进行，不需要进行排空
        // 删除文件夹，删除之前需要先删除其子元素
        oss.deleteObject("hgshequ-bucket",questionId.toString());

        oss.shutdown();

        personMapper.deleteQuestion(questionId,userId);
        // 删除问题成功后删除评论
        personMapper.deleteComment(questionId);
    }

}
